//
//  WKNodeSelectVC.m
//  WuKongBase
//
//  Created by wangfei on 2025/9/21.
//

#import "WKNodeSelectVC.h"
#import "WKServerNode.h"
#import "WKNodeSelectCell.h"
#import "Masonry/Masonry.h"
#import "WKPingTools.h"

@interface WKNodeSelectVC () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray<WKServerNode *> *nodeList;
@property (nonatomic, strong) UIView *tipsContainerView;
@property (nonatomic, strong) UIActivityIndicatorView *loadingIndicator;
@property (nonatomic, strong) UILabel *emptyStateLabel;
@property (nonatomic, strong)WKPingTools *tools;
@end

@implementation WKNodeSelectVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0];
    
//    [self setupNavigationBar];
    [self setupSubviews];
    [self loadNodeData];
}
- (NSString *)langTitle {
    return LLang(@"选择节点");
}
- (void)setupSubviews {
    // 速度提示区域
    [self setupTipsView];
    
    // 表格视图
    [self setupTableView];
    
    // 加载指示器
    [self setupLoadingIndicator];
    
    // 空状态提示
    [self setupEmptyStateView];
}

- (void)setupTipsView {
    self.tipsContainerView = [[UIView alloc] init];
    self.tipsContainerView.backgroundColor = [WKApp shared].config.cellBackgroundColor;
    self.tipsContainerView.layer.cornerRadius = 8;
    self.tipsContainerView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.tipsContainerView.layer.shadowOpacity = 0.05;
    self.tipsContainerView.layer.shadowRadius = 4;
    self.tipsContainerView.layer.shadowOffset = CGSizeMake(0, 2);
    [self.view addSubview:self.tipsContainerView];
    
    // 提示文字
    UILabel *tipsLabel = [[UILabel alloc] init];
    tipsLabel.text = @"节点速度越快响应越迅速，建议优先选择速度快且稳定的节点。切换节点后需要重新连接。";
    tipsLabel.font = [UIFont systemFontOfSize:14];
    tipsLabel.textColor = [UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0];
    tipsLabel.numberOfLines = 0;
    [self.tipsContainerView addSubview:tipsLabel];
    
    // 速度指示器容器
    UIView *speedIndicatorsView = [[UIView alloc] init];
    [self.tipsContainerView addSubview:speedIndicatorsView];
    
    // 快速指示器
    [self addSpeedIndicatorToView:speedIndicatorsView
                           color:[UIColor colorWithRed:46/255.0 green:204/255.0 blue:113/255.0 alpha:1.0]
                            text:@"快"
                           index:0];
    
    // 中等速度指示器
    [self addSpeedIndicatorToView:speedIndicatorsView
                           color:[UIColor colorWithRed:241/255.0 green:196/255.0 blue:15/255.0 alpha:1.0]
                            text:@"中"
                           index:1];
    
    // 慢速指示器
    [self addSpeedIndicatorToView:speedIndicatorsView
                           color:[UIColor colorWithRed:231/255.0 green:76/255.0 blue:60/255.0 alpha:1.0]
                            text:@"慢"
                           index:2];
    
    // 约束设置
    self.tipsContainerView.translatesAutoresizingMaskIntoConstraints = NO;
    tipsLabel.translatesAutoresizingMaskIntoConstraints = NO;
    speedIndicatorsView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [NSLayoutConstraint activateConstraints:@[
        [self.tipsContainerView.topAnchor constraintEqualToAnchor:self.navigationBar.safeAreaLayoutGuide.bottomAnchor constant:0],
        [self.tipsContainerView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:16],
        [self.tipsContainerView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],
        
        [tipsLabel.topAnchor constraintEqualToAnchor:self.tipsContainerView.topAnchor constant:16],
        [tipsLabel.leadingAnchor constraintEqualToAnchor:self.tipsContainerView.leadingAnchor constant:16],
        [tipsLabel.trailingAnchor constraintEqualToAnchor:self.tipsContainerView.trailingAnchor constant:-16],
        
        [speedIndicatorsView.topAnchor constraintEqualToAnchor:tipsLabel.bottomAnchor constant:16],
        [speedIndicatorsView.leadingAnchor constraintEqualToAnchor:self.tipsContainerView.leadingAnchor constant:16],
        [speedIndicatorsView.trailingAnchor constraintEqualToAnchor:self.tipsContainerView.trailingAnchor constant:-16],
        [speedIndicatorsView.bottomAnchor constraintEqualToAnchor:self.tipsContainerView.bottomAnchor constant:-16],
        [speedIndicatorsView.heightAnchor constraintEqualToConstant:24]
    ]];
}

- (void)addSpeedIndicatorToView:(UIView *)parentView color:(UIColor *)color text:(NSString *)text index:(NSInteger)index {
    UIView *indicatorContainer = [[UIView alloc] init];
    indicatorContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [parentView addSubview:indicatorContainer];
    
    // 圆点
    UIView *dotView = [[UIView alloc] init];
    dotView.backgroundColor = color;
    dotView.layer.cornerRadius = 6;
    dotView.translatesAutoresizingMaskIntoConstraints = NO;
    [indicatorContainer addSubview:dotView];
    
    // 文字
    UILabel *textLabel = [[UILabel alloc] init];
    textLabel.text = text;
    textLabel.font = [UIFont systemFontOfSize:13];
    textLabel.textColor = [UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0];
    textLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [indicatorContainer addSubview:textLabel];
    
    // 内部约束
    [NSLayoutConstraint activateConstraints:@[
        [dotView.widthAnchor constraintEqualToConstant:12],
        [dotView.heightAnchor constraintEqualToConstant:12],
        [dotView.centerYAnchor constraintEqualToAnchor:indicatorContainer.centerYAnchor],
        [dotView.leadingAnchor constraintEqualToAnchor:indicatorContainer.leadingAnchor],
        
        [textLabel.leadingAnchor constraintEqualToAnchor:dotView.trailingAnchor constant:6],
        [textLabel.centerYAnchor constraintEqualToAnchor:indicatorContainer.centerYAnchor],
        [textLabel.trailingAnchor constraintEqualToAnchor:indicatorContainer.trailingAnchor]
    ]];
    
    // 在父视图中的约束
    [NSLayoutConstraint activateConstraints:@[
        [indicatorContainer.centerYAnchor constraintEqualToAnchor:parentView.centerYAnchor],
        [indicatorContainer.leadingAnchor constraintEqualToAnchor:parentView.leadingAnchor constant:index * 80]
    ]];
}

- (void)setupTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 80;
    [self.tableView registerClass:[WKNodeSelectCell class] forCellReuseIdentifier:@"WKNodeSelectCell"];
    [self.view addSubview:self.tableView];
    
    self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(self.tipsContainerView.mas_bottom);
    }];
}

- (void)setupLoadingIndicator {
    self.loadingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleLarge];
    self.loadingIndicator.hidesWhenStopped = YES;
    self.loadingIndicator.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.loadingIndicator];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.loadingIndicator.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
        [self.loadingIndicator.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor]
    ]];
}

- (void)setupEmptyStateView {
    self.emptyStateLabel = [[UILabel alloc] init];
    self.emptyStateLabel.text = @"暂无可用节点，请稍后重试";
    self.emptyStateLabel.font = [UIFont systemFontOfSize:16];
    self.emptyStateLabel.textColor = [UIColor lightGrayColor];
    self.emptyStateLabel.hidden = YES;
    self.emptyStateLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.emptyStateLabel];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.emptyStateLabel.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
        [self.emptyStateLabel.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor]
    ]];
}

- (void)loadNodeData {
    [self.loadingIndicator startAnimating];
    self.tableView.hidden = YES;
    self.emptyStateLabel.hidden = YES;
    
    self.nodeList = [WKApp shared].config.serverNodes;
    if (self.nodeList.count > 0) {
        self.tableView.hidden = NO;
        [self.tableView reloadData];
        [self nodeTestIndex:0];
    } else {
        [self.loadingIndicator stopAnimating];
        self.emptyStateLabel.hidden = NO;
    }
    
   
}

- (void)nodeTestIndex:(NSInteger)index{
    if (index >= self.nodeList.count){
        [self.loadingIndicator stopAnimating];
        return;
    }
    
    WKServerNode *node = self.nodeList[index];
    
    self.tools = [[WKPingTools alloc] initWithHostName:[node.ip componentsSeparatedByString:@":"].firstObject];
       
    // 可选配置
    self.tools.debugLog = YES; // 开启调试日志（控制台输出详细信息）
    self.tools.timeout = [HDPingTimeInterval intervalWithMillisecond:2000]; // 超时时间设为 2 秒
    self.tools.stopWhenError = NO; // 出错时不停止（继续下一次 Ping）
    self.tools.showNetworkActivityIndicator = HDNetworkActivityIndicatorStatusAuto; // 自动显示状态栏指示器
       
    [self.tools startWithComplete:^(HDPingResponse * _Nullable response, NSError * _Nullable error) {
        if (error){
            node.delay = @"";
            node.isAvailable = false;
            NSLog(@"Ping 失败：%@", error.localizedDescription);
        }else{
            node.delay = [NSString stringWithFormat:@"%.fms",response.responseTime.value];
            node.isAvailable = true;
        }
        [self nodeTestIndex:index + 1];
        [self.tableView reloadData];
    }];
}
#pragma mark - UITableView DataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.nodeList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WKNodeSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WKNodeSelectCell" forIndexPath:indexPath];
    WKServerNode *node = self.nodeList[indexPath.row];
    [cell configureWithNode:node];
        if ([node.ip isEqualToString:[WKApp shared].config.currentServerIP]){
        cell.isCurrent = YES;
    }else{
        cell.isCurrent = NO;
    }
    return cell;
}

#pragma mark - UITableView Delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WKServerNode *selectedNode = self.nodeList[indexPath.row];
    
    // 检查节点是否可用
    if (!selectedNode.isAvailable) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                       message:@"该节点当前不可用，请选择其他节点"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        return;
    }
    
    if (![[WKApp shared].config.currentServerIP isEqualToString:selectedNode.ip]){
        [self setupAppConfig:selectedNode];
    }
}

// 初始化App配置（使用当前选中的节点）
- (void)setupAppConfig:(WKServerNode *)node {
    NSString *baseURL = [NSString stringWithFormat:@"%@://%@/v1/", node.https ? @"https" : @"http", node.ip];
    NSString *webURL = [NSString stringWithFormat:@"%@://%@/web/", node.https ? @"https" : @"http", node.ip];
    
    WKAppConfig *config = [WKAppConfig new];
    config.apiBaseUrl = baseURL;                // api地址
    config.fileBaseUrl = baseURL;               // 文件上传地址
    config.fileBrowseUrl = baseURL;             // 文件预览地址
    config.imageBrowseUrl = baseURL;            // 图片预览地址
    config.reportUrl = [NSString stringWithFormat:@"%@report/html", baseURL]; // 举报地址
    config.privacyAgreementUrl = [NSString stringWithFormat:@"%@privacy_policy.html", webURL]; // 隐私协议
    config.userAgreementUrl = [NSString stringWithFormat:@"%@user_agreement.html", webURL]; // 用户协议
    config.serverNodes = self.nodeList;
    config.currentServerIP = node.ip;
    config.currentHTTPSOn = node.https;
    [WKApp shared].config = config;
    [[WKConnectionManager sharedManager] disconnect:YES];
    [[WKApp shared] appInit];
    
}
#pragma mark - Actions

- (void)backAction {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Helper

- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    [color setFill];
    UIRectFill(CGRectMake(0, 0, size.width, size.height));
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@end

